<template>
    <div>
        <TheElDialog
            ref="dialog"
            :title="title"
            :visible.sync="centerDialogVisible"
            @close="handleCenterDialogClose"
            v-bind="$attrs"
        >
            <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                    <ul class="text-block-wrapper">
                        <li class="text-block">
                            <span class="text-title">账户名称：</span>
                            <span class="text-content">{{ accountName }}</span>
                        </li>
                    </ul>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                    <ul class="text-block-wrapper">
                        <li class="text-block">
                            <span class="text-title">账户编号：</span>
                            <span class="text-content">{{ accountNumber }}</span>
                        </li>
                    </ul>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                    <ul class="text-block-wrapper">
                        <li class="text-block">
                            <span class="text-title">账户ID：</span>
                            <span class="text-content">{{ accountId }}</span>
                        </li>
                    </ul>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
                    <ul class="text-block-wrapper">
                        <li class="text-block">
                            <span class="text-title">当前余额：</span>
                            <span class="text-content">¥ {{ accountOutEnd | keep2decimalPlaces }}</span>
                        </li>
                    </ul>
                </el-col>
            </el-row>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column type="index"></el-table-column>
                <!--
                //     // 仓库 depotInfo 
                //     // 单据编号 documentNo
                    //     // 交易类型 type === 1, 2, 3, 4
                    //     // 类型说明 typeDescription
                    //     // 对方账号 reciprocalNumberReversal
                    //     // 交易金额 transactionAccount
                    //     // 交易余额 accountBalance
                    //     // 单据日期 documentDate  -->
                <el-table-column
                    prop="depotInfo"
                    label="仓库"
                    :filters="optionsDepots.map(item => ({text: item.name, value: item._id}))"
                    :filter-method="filterDepotInfo"
                >
                    <template v-slot="{row}">
                        {{ row.depotInfo && row.depotInfo.name }}
                    </template>
                </el-table-column>
                <el-table-column prop="documentNo" label="单据编号">
                    <template v-slot="{row}">
                        <TextButton @click="onClickDetail(row, '查看单据')">
                            {{ row.documentNo }}
                        </TextButton>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="documentDate"
                    label="单据日期"
                    :filters="documentDateFilters"
                    :filter-method="filterDocumentDate"
                >
                    <template v-slot="{row}">
                        {{ row.documentDate | formatDateFillStr }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="typeDescription"
                    label="交易类型"
                    :filters="[
                        {text: '收入', value: '1'},
                        {text: '支出', value: '2'},
                        {text: '转账付款', value: '3'},
                        {text: '转账收款', value: '4'},
                        {text: '期初金额', value: ''}
                    ]"
                    :filter-method="filterType"
                    filter-placement="bottom-end"
                >
                    <template v-slot="{row}">
                        <el-tag :type="row.type | showAccountPlayType" disable-transitions>{{
                            row.typeDescription
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="ReciprocalNumberReversal" label="对方账号（单位）">
                    <template v-slot="{row}">
                        <template v-if="Array.isArray(row.ReciprocalNumberReversal)">
                            <TextButton
                                v-for="(item, index) in deduplication(row.ReciprocalNumberReversal)"
                                :key="index"
                                @click="onClickReciprocalDetail(item, '查看对方账号（单位）')"
                            >
                                {{ item.name }} {{ item.count > 1 ? `+${item.count}` : '' }}
                            </TextButton>
                        </template>
                        <template v-else>
                            <TextButton
                                v-if="row.ReciprocalNumberReversal && row.ReciprocalNumberReversal.name"
                                @click="onClickReciprocalDetail(row.ReciprocalNumberReversal, '查看对方账号（单位）')"
                            >
                                {{ row.ReciprocalNumberReversal && row.ReciprocalNumberReversal.name }}
                            </TextButton>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="transactionAccount" label="交易金额">
                    <template v-slot="{row}">
                        {{ row.transactionAccount | keep2decimalPlaces }}
                    </template>
                </el-table-column>
                <el-table-column prop="accountBalance" label="交易余额">
                    <template v-slot="{row}">
                        {{ row.accountBalance | keep2decimalPlaces }}
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
                <el-button :loading="centerDialogLoading" type="primary" @click="onClickPrint('dialog')" plain
                    >打 印</el-button
                >
            </span>
        </TheElDialog>
        <ItemOutDialog
            width="21cm"
            :title="documentTitle"
            :visible.sync="visibleItemOutDetail"
            :data-source="dataSourceDetail"
            :optionsPersons="optionsPersons"
            :optionsVendors="optionsVendors"
            :optionsProjects="optionsProjects"
            :optionsAccounts="optionsAccounts"
            :optionsDepots="optionsDepots"
            closeOnPressEscape
            closeOnClickModal
        ></ItemOutDialog>
        <ItemInDialog
            width="21cm"
            :title="documentTitle"
            :visible.sync="visibleItemInDetail"
            :data-source="dataSourceDetail"
            :optionsPersons="optionsPersons"
            :optionsCustomers="optionsCustomers"
            :optionsProjects="optionsProjects"
            :optionsAccounts="optionsAccounts"
            :optionsDepots="optionsDepots"
            closeOnPressEscape
            closeOnClickModal
        ></ItemInDialog>
        <TransferDialog
            width="21cm"
            :title="documentTitle"
            :visible.sync="visibleTransferDetail"
            :data-source="dataSourceDetail"
            :optionsPersons="optionsPersons"
            :optionsAccounts="optionsAccounts"
            :optionsDepots="optionsDepots"
            closeOnPressEscape
            closeOnClickModal
        ></TransferDialog>
        <!-- 查看账户信息 -->
        <AccountDialog
            width="21cm"
            :title="documentTitle"
            :visible.sync="visibleAccountDetail"
            :data-source="dataSourceDetail"
            :optionsPersons="optionsPersons"
            closeOnPressEscape
            closeOnClickModal
        ></AccountDialog>
    </div>
</template>
<script>
import ItemOutDialog from '@/views/financial/item-out/FunctionDialog';
import ItemInDialog from '@/views/financial/item-in/FunctionDialog';
import TransferDialog from '@/views/financial/transfer/FunctionDialog';
import AccountDialog from '@/views/system/account/FunctionDialog';
import dialogToPrint from '@/utils/dialogToPrint';
import moment from 'moment';
export default {
    name: 'center-dialog',
    props: {
        title: {type: String, default: ''},
        visible: {type: Boolean, default: false},
        dataSource: {type: Object, required: true},

        optionsPersons: {type: Array, required: true, default: () => []},
        optionsCustomers: {type: Array, required: true, default: () => []},
        optionsVendors: {type: Array, required: true, default: () => []},
        optionsProjects: {type: Array, required: true, default: () => []},
        optionsAccounts: {type: Array, required: true, default: () => []},
        optionsDepots: {type: Array, required: true, default: () => []}
    },
    components: {
        ItemOutDialog,
        ItemInDialog,
        TransferDialog,
        AccountDialog
    },
    data() {
        return {
            accountNumber: '',
            accountId: '',
            accountName: '',
            accountOutEnd: 0,
            tableData: [],
            documentDateFilters: [],

            // 新建弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},

            visibleItemOutDetail: false, // 查看支出单据
            visibleItemInDetail: false, // 查看收入单据
            visibleTransferDetail: false, // 查看转账单据
            visibleAccountDetail: false, // 查看账户信息弹出
            dataSourceDetail: {},
            documentTitle: ''
        };
    },
    computed: {
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        isDetail() {
            return typeof this.title === 'string' && this.title.includes('查看');
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                this.accountNumber = val.number;
                this.accountId = val._id;
                this.accountName = val.name;
                this.accountOutEnd = val.outEnd;
                this.tableData = val.history;
                this.documentDateFilters = (val.history || []).reduce((acc, item) => {
                    if (!item.documentDate) {
                        return acc;
                    }
                    const value = moment(item.documentDate).format('YYYY/MM/DD');
                    const newItem = {text: value, value};
                    const hit = acc.findIndex(c => c.text === newItem.text);
                    if (hit === -1) {
                        acc.push(newItem);
                    }
                    return acc;
                }, []);
            },
            immediate: true
        }
    },
    methods: {
        deduplication(arr, prop = '_id') {
            console.log('arr', arr);

            const result = arr.reduce((acc, item) => {
                const hit = acc.find(c => c[prop] === item[prop]);
                if (!hit) {
                    item.count = 1;
                    acc.push(item);
                } else {
                    hit.count += 1;
                }
                return acc;
            }, []);
            console.log('result', result);
            return result;
        },
        filterDocumentDate(value, row) {
            return moment(row.documentDate).format('YYYY/MM/DD') === value;
        },
        filterDepotInfo(value, row) {
            return row?.depotInfo?._id === value;
        },
        filterType(value, row) {
            return row.type === value;
        },
        onClickReciprocalDetail(dataSourceDetail, title) {
            console.log('dataSourceDetail', dataSourceDetail);
            this.documentTitle = title;
            this.dataSourceDetail = {...dataSourceDetail};
            this.visibleAccountDetail = true;
        },
        onClickPrint() {
            dialogToPrint.call(this, this.$refs.dialog, [
                ...Array.from(document.querySelectorAll('.dialog-footer')),
                ...Array.from(document.querySelectorAll('.el-dialog__close'))
            ]);
        },
        onClickDetail(row) {
            this.dataSourceDetail = {...row.itemInfo};

            switch (row.type) {
                // 收入
                case '1': {
                    this.documentTitle = '查看收入单据';
                    this.visibleItemOutDetail = false;
                    this.visibleItemInDetail = true;
                    this.visibleTransferDetail = false;
                    break;
                }
                // 支出
                case '2': {
                    this.documentTitle = '查看支出单据';
                    this.visibleItemOutDetail = true;
                    this.visibleItemInDetail = false;
                    this.visibleTransferDetail = false;
                    break;
                }
                // 转账付款
                // 收款付款
                case '3':
                case '4': {
                    this.documentTitle = `查看${row.type === 3 ? '转账付款' : '转账收款'}单据`;
                    this.visibleItemOutDetail = false;
                    this.visibleItemInDetail = false;
                    this.visibleTransferDetail = true;
                    break;
                }

                default:
                    break;
            }
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');
            this.tableData = [];
        },
        indexMethod(index) {
            return this.tableData.length - index;
        }
    }
};
</script>
